package com.wlz.single;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 单线程下的BIO
 *
 */
public class BioServerSingle {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        InputStream in=null;
        OutputStream out=null;

        Socket socket=null;
        try {
            // 创建一个新的ServerSocket，绑定一个InetSocketAddress，监听8000端口上的连接请求
            serverSocket=new ServerSocket(8080);

            // accept 专门负责通信
            while (true){

                System.out.println("等待连接---");
                socket=serverSocket.accept();//阻塞（这里会阻塞以释放CPU资源） 做了什么事情 三次握手
                System.out.println("连接成功---");

                System.out.println("等待数据传输---");
                // =====②:getInputStrea()函数获取客户端传送的输入流
                in = socket.getInputStream();
                byte[] buffer=new byte[1024];
                int length=0;
                while ((length=in.read(buffer))>0){//阻塞
                    System.out.println("数据传输完成---");
                    System.out.println("input is:"+new String(buffer));
                    out =socket.getOutputStream();
                    out.write("success".getBytes());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
